package com.qf.xml;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.Filter;

public class WebXml extends AbstractDispatcherServletInitializer {
    /**
     * 创建web层容器 - 子容器
     *      <servlet>
     *         <servlet-name>dispatcherServlet</servlet-name>
     *         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     *
     *         <init-param>
     *             <param-name>contextConfigLocation</param-name>
     *             <param-value>classpath:springmvc.xml</param-value>
     *         </init-param>
     *
     *         <load-on-startup>1</load-on-startup>
     *     </servlet>
     * @return
     */
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ioc = new AnnotationConfigWebApplicationContext();
        ioc.register(SpringMVCConfig.class);
        return ioc;
    }

    /**
     * 配置的是前端控制器的访问路径
     *    <url-pattern>/</url-pattern>-->
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 创建service层的容器 - 父容器
     *          <listener>
 *                  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 *              </listener>
 *              <context-param>
 *                  <param-name>contextConfigLocation</param-name>
 *                  <param-value>classpath:spring.xml</param-value>
 *              </context-param>
     * @return
     */
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext ioc = new AnnotationConfigWebApplicationContext();
        ioc.register(SpringConfig.class);
        return ioc;
    }

    /**
     * 配置拦截前端给控制器的过滤器
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("utf-8");
        encodingFilter.setForceEncoding(true);
        return new Filter[]{encodingFilter};
    }
}
